package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户参数解析器
 * 用于解析请求映射方法中声明的形式参数UserInfo类型参数解析成当前登录用户的对象信息并注入
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //返回值boolean 类型: true:表示支持解析指定类型 false: 表示不支持指定类型

    //支持哪种类型参数
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //表示当前解析器能解析哪种类型参数
        return parameter.getParameterType() == UserInfo.class
                && parameter.hasParameterAnnotation(UserParam.class)
                ;
    }
    //执行参数解析逻辑, 并注入到参数中
    //执行前提: 必须满足supportsParameter方法返回true
    //获取当前登入用户对象信息
    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        //获取当前登录对象
        HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = req.getHeader("token");
        //返回值就是请求映射方法声明形式参数什么的UserInfo对象的值
        //返回当前登录用户对象

        //获取token对象返回
        return userInfoRedisService.getUserByToken(token);
    }
}
